"""
    Created By Khun on 2020/4/7
"""

__author__ = 'Khun'

from contextlib import contextmanager
from datetime import datetime

from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy

__all__ = ['db', 'Base']


class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e


db = SQLAlchemy()


class Base(db.Model):
    __abstract__ = True

    def __init__(self, *args, **kwargs):
        self.create_time = datetime.now()
        super().__init__(*args, **kwargs)

    def set_attr(self, attrs_dict):
        for k, v in attrs_dict.items():
            if hasattr(self, k) and k not in [i for i in ['tid', 'uid', 'id']]:
                setattr(self, k, v)

    # def __getitem__(self, item):
    #     return getattr(self, item)
